<template>
  <div>
    <a-modal
      v-if="modelType !== false"
      v-model="visible"
      :width="modalWidth"
      :title="titleFormat"
      @cancel="handleClose"
      :destroyOnClose="true"
      :maskClosable="false"
    >
      <approvalStep
        v-if="formType === FORMTYPE.CHECK && workState"
        :workState="workState"
      />
      <form-group
        :formOptions="formOptionsFormat"
        :ref="`formGroup`"
        :formDeal="formDeal"
        :formType="formType"
        :config="config"
        @add="handleAdd"
        @remove="handleRemove"
        @update="handleUpdate"
        @updateAll="handleUpdateAll"
        @supplement="handleSupplement"
        @spinState="handleSpinState"
      />
      <template slot="footer">
        <a-button @click="handleClose"> 取消 </a-button>
        <a-button
          type="primary"
          @click="handleSave"
          v-if="[FORMTYPE.CHECK, FORMTYPE.PREVIEW].indexOf(formType) == -1"
          :disabled="spinning"
        >
          保存
        </a-button>
      </template>
    </a-modal>
    <form-group
      v-else
      :formOptions="formOptionsFormat"
      :ref="`formGroup`"
      :formDeal="formDeal"
      :formType="formType"
      :config="config"
      @add="handleAdd"
      @remove="handleRemove"
      @update="handleUpdate"
      @updateAll="handleUpdateAll"
      @supplement="handleSupplement"
    />
  </div>
</template>

<script>
import _ from 'lodash';
import { mapGetters } from 'vuex';
import formGroup from './form-group.vue';
import { DATA_CODE_SUCCESS, FORMTYPE } from '@/utils/consts';
import {
  formWorkAdd,
  formWorkEdit,
  formWorkDetail
} from '@/services/formService';
import approvalStep from './approval-step.vue';

export default {
  props: ['id', 'config', 'formOptions', 'formDeal', 'formType', 'modelType'],
  name: 'formModal',
  components: {
    formGroup,
    approvalStep
  },
  computed: {
    ...mapGetters('account', ['dictConfig']),
    showSubmit() {
      return this.formType === FORMTYPE.ADD || this.formType === FORMTYPE.EDIT;
    },
    formOptionsFormat() {
      if (this.formType === FORMTYPE.PREVIEW) {
        return _.cloneDeep(this.formOptions);
      }
      return this.formOptions;
    },
    titleFormat() {
      let titleStr = '';
      switch (this.formType) {
        case FORMTYPE.ADD:
          titleStr = '新增';
          break;
        case FORMTYPE.EDIT:
          titleStr = '编辑';
          break;
        case FORMTYPE.CHECK:
          titleStr = '查看';
          break;
        default:
          titleStr = '预览';
          break;
      }
      return titleStr;
    }
  },
  data() {
    return {
      visible: false,
      submitForm: {},
      FORMTYPE,
      submitParams: {},
      workState: {},
      modalWidth: 1200,
      submitData: {},
      spinning: false
    };
  },
  methods: {
    show(data, submitParams = { flag: 0 }) {
      this.setModalWidth();
      this.submitForm = {};
      this.submitData = {};
      this.submitParams = submitParams;
      this.visible = true;
      this.$nextTick(async () => {
        if (this.formType === FORMTYPE.EDIT || this.formType === FORMTYPE.CHECK) {
          const response = await formWorkDetail({ id: this.id });
          if (response.data.code === DATA_CODE_SUCCESS) {
            this.submitForm = response.data.data;
            this.workState = response.data.data.workState || {};
            this.$emit('setData', response.data.data.bigInfo);
            this.setVin(response.data.data.bigInfo);
            this.$refs.formGroup.initial(response.data.data.bigInfo);
          }
        } else {
          this.$refs.formGroup.initial(data);
        }
      });
    },
    handleAdd(oriArray, oriObj, index) {
      const clone = _.cloneDeep(oriObj);
      oriArray.splice(index, 0, clone);
    },
    handleUpdate(option, index) {
      this.$set(this.formOptions, index, option);
    },
    handleUpdateAll(contractData, data) {
      this.$refs.formGroup.setForm({ data: contractData });
      this.$emit('setData', data);
    },
    handleSupplement(data) {
      Object.assign(this.submitData, data);
    },
    handleRemove(oriArray, index) {
      // oriArray.splice(index, 1);
      this.$set(oriArray, index, {});
    },
    handleClose() {
      this.visible = false;
    },
    setVin(data) {
      const vinObj = this.formDeal.beforeList.find(
        (li) => li.item.isLock === true
      );
      if (vinObj) {
        this.$refs.formGroup.setParams({
          [vinObj.item.aliasName]:
            data[`${vinObj.key}_${vinObj.item.inputName}`]
        });
      }
    },
    combineByAliasName({ aliasName, formData }) {
      const params = { [aliasName]: { items: [] } };
      this.formOptions.forEach((option, optIdx) => {
        if (option.aliasName === aliasName) {
          option.rows.forEach((row, rowIdx) => {
            if (rowIdx > 0) {
              const rowData = {};
              if (row.children) {
                row.children.forEach((item) => {
                  rowData[item.aliasName] = formData[`${option.inputName}_${optIdx}_${rowIdx - 1}_${item.inputName}`];
                });
                params[aliasName].items.push(rowData);
              }
            }
          });
        }
      });
      return params;
    },
    formatData(data) {
      const keys = Object.keys(data);
      const format = {};
      keys.forEach((cur) => {
        const [optionKey, optIdx, rowIdx, itemKey] = cur.split('_');
        if (!format[optionKey]) {
          format[optionKey] = [];
        }
        if (!format[optionKey][optIdx]) {
          format[optionKey][optIdx] = [];
        }
        if (!format[optionKey][optIdx][rowIdx]) {
          format[optionKey][optIdx][rowIdx] = {};
        }
        format[optionKey][optIdx][rowIdx][itemKey] = data[cur];
      });
      Object.keys(format).forEach((optionKey) => {
        format[optionKey] = _.compact(format[optionKey]);
        format[optionKey].forEach((option, idx) => {
          format[optionKey][idx] = _.compact(option);
        });
      });
      return format;
    },
    handleSave() {
      this.$refs.formGroup.validateForm().then(async (res) => {
        let data = {
          bigInfo: res,
          businessFlowId: this.config.businessFlowId,
          businessFlowSubId: this.config.businessFlowSubId,
          typeId: this.config.formWorkTypeId,
          typeName: this.$router.currentRoute.name,
          workType: this.config.workType,
          workDetail: {},
          ...this.submitData
        };
        // 定制逻辑：提交前处理列表单带入的数据
        let reqFunc = null;
        this.formOptions.forEach((option) => {
          if (option.isTable && option.aliasName) {
            // eslint-disable-next-line max-len
            Object.assign(
              data,
              this.combineByAliasName({
                aliasName: option.aliasName,
                formData: res
              })
            );
          }
        });
        if (!this.submitForm.id) {
          reqFunc = formWorkAdd;
        } else {
          reqFunc = formWorkEdit;
          data = { ...this.submitParams, ...this.submitForm };
          data.bigInfo = res;
        }
        data.workDetail = this.formatData(res);
        const response = await reqFunc(data);
        if (response.data.code === DATA_CODE_SUCCESS) {
          this.$emit('refresh');
          this.visible = false;
        } else {
          this.$message.error(response.data.message);
        }
      });
    },
    setModalWidth() {
      this.modalWidth = window.innerWidth - parseInt(window.innerWidth * 0.1, 10);
    },
    handleSpinState(val) {
      this.spinning = val;
    }
  },
  created() {
    window.addEventListener('resize', this.setModalWidth);
  },
  destroyed() {
    window.removeEventListener('resize', this.setModalWidth);
  }
};
</script>
